#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from enum import Enum
from datetime import datetime, timedelta
from PySide6.QtCore import QObject, Signal, QTimer, Slot, QTime

class TimerState(Enum):
    """计时器状态枚举"""
    IDLE = 0      # 空闲状态
    WORKING = 1   # 工作状态
    BREAKING = 2  # 休息状态
    PAUSED = 3    # 暂停状态

class TimerMode(Enum):
    """计时器模式枚举"""
    POMODORO = 0  # 番茄钟模式（倒计时）
    FLOWDORO = 1  # Flowdoro模式（正计时）

class Timer(QObject):
    """计时器模型，负责管理番茄钟和Flowdoro计时"""
    
    # 信号定义
    stateChanged = Signal(TimerState)  # 状态变化信号
    tick = Signal(int, int)  # 计时信号，参数：剩余/已用时间（秒），总时间（秒）
    workFinished = Signal()  # 工作完成信号
    breakFinished = Signal()  # 休息完成信号
    
    def __init__(self, config_manager, db_manager):
        """初始化计时器
        
        Args:
            config_manager: 配置管理器实例
            db_manager: 数据库管理器实例
        """
        super().__init__()
        
        self.config_manager = config_manager
        self.db_manager = db_manager
        
        # 初始化计时器
        self.timer = QTimer(self)
        self.timer.setInterval(1000)  # 1秒间隔
        self.timer.timeout.connect(self._on_timer_tick)
        
        # 初始化状态
        self.state = TimerState.IDLE
        self.mode = TimerMode.POMODORO if config_manager.get("general", "default_mode") == "pomodoro" else TimerMode.FLOWDORO
        
        # 计时相关变量
        self.start_time = None
        self.elapsed_seconds = 0
        self.total_seconds = 0
        self.current_work_session_id = None
        self.current_break_session_id = None
    
    def set_mode(self, mode):
        """设置计时器模式
        
        Args:
            mode: TimerMode 枚举值或字符串 'pomodoro'/'flowdoro'
        """
        if isinstance(mode, str):
            self.mode = TimerMode.POMODORO if mode.lower() == "pomodoro" else TimerMode.FLOWDORO
        else:
            self.mode = mode
        
        # 更新配置
        self.config_manager.set("general", "default_mode", "pomodoro" if self.mode == TimerMode.POMODORO else "flowdoro")
    
    def start_work(self):
        """开始工作计时"""
        if self.state == TimerState.WORKING:
            return
        
        # 如果当前是暂停状态，则恢复计时
        if self.state == TimerState.PAUSED and self.current_work_session_id is not None:
            self.state = TimerState.WORKING
            self.start_time = datetime.now() - timedelta(seconds=self.elapsed_seconds)
            self.timer.start()
            self.stateChanged.emit(self.state)
            return
        
        # 开始新的工作会话
        self.state = TimerState.WORKING
        self.start_time = datetime.now()
        self.elapsed_seconds = 0
        
        if self.mode == TimerMode.POMODORO:
            # 番茄钟模式，设置倒计时总时间
            self.total_seconds = self.config_manager.get("pomodoro", "work_minutes") * 60
        else:
            # Flowdoro模式，没有预设的总时间
            self.total_seconds = 0
        
        # 创建工作会话记录
        mode_str = "pomodoro" if self.mode == TimerMode.POMODORO else "flowdoro"
        self.current_work_session_id = self.db_manager.start_work_session(mode_str)
        
        # 启动计时器
        self.timer.start()
        self.stateChanged.emit(self.state)
    
    def start_break(self):
        """开始休息计时"""
        if self.state == TimerState.BREAKING:
            return
        
        # 如果当前是工作状态，先结束工作
        if self.state == TimerState.WORKING and self.current_work_session_id is not None:
            self.db_manager.end_work_session(self.current_work_session_id)
        
        # 开始新的休息会话
        self.state = TimerState.BREAKING
        self.start_time = datetime.now()
        self.elapsed_seconds = 0
        
        if self.mode == TimerMode.POMODORO:
            # 番茄钟模式，设置倒计时总时间
            self.total_seconds = self.config_manager.get("pomodoro", "break_minutes") * 60
        else:
            # Flowdoro模式，休息时间为工作时间的一定比例
            break_ratio = self.config_manager.get("flowdoro", "break_ratio")
            min_break = self.config_manager.get("flowdoro", "min_break_minutes") * 60
            max_break = self.config_manager.get("flowdoro", "max_break_minutes") * 60
            
            # 计算休息时间
            if self.elapsed_seconds > 0:
                break_seconds = int(self.elapsed_seconds * break_ratio)
                break_seconds = max(min_break, min(break_seconds, max_break))
                self.total_seconds = break_seconds
            else:
                self.total_seconds = min_break
        
        # 创建休息会话记录
        if self.current_work_session_id is not None:
            self.current_break_session_id = self.db_manager.start_break_session(self.current_work_session_id)
        
        # 启动计时器
        self.timer.start()
        self.stateChanged.emit(self.state)
    
    def pause(self):
        """暂停计时"""
        if self.state not in [TimerState.WORKING, TimerState.BREAKING]:
            return
        
        self.timer.stop()
        self.state = TimerState.PAUSED
        self.stateChanged.emit(self.state)
    
    def resume(self):
        """恢复计时"""
        if self.state != TimerState.PAUSED:
            return
        
        # 恢复之前的状态
        if self.current_work_session_id is not None:
            self.state = TimerState.WORKING
        elif self.current_break_session_id is not None:
            self.state = TimerState.BREAKING
        else:
            self.state = TimerState.IDLE
            return
        
        # 更新开始时间，保持已经过的时间不变
        self.start_time = datetime.now() - timedelta(seconds=self.elapsed_seconds)
        
        # 启动计时器
        self.timer.start()
        self.stateChanged.emit(self.state)
    
    def stop(self):
        """停止计时"""
        self.timer.stop()
        
        # 结束当前会话
        if self.state == TimerState.WORKING and self.current_work_session_id is not None:
            self.db_manager.end_work_session(self.current_work_session_id, completed=False)
            self.current_work_session_id = None
        elif self.state == TimerState.BREAKING and self.current_break_session_id is not None:
            self.db_manager.end_break_session(self.current_break_session_id, completed=False)
            self.current_break_session_id = None
        
        # 重置状态
        self.state = TimerState.IDLE
        self.elapsed_seconds = 0
        self.total_seconds = 0
        self.start_time = None
        
        self.stateChanged.emit(self.state)
    
    def skip_break(self):
        """跳过休息"""
        if self.state != TimerState.BREAKING:
            return
        
        # 结束当前休息会话
        if self.current_break_session_id is not None:
            self.db_manager.end_break_session(self.current_break_session_id, completed=False)
            self.current_break_session_id = None
        
        # 重置状态
        self.state = TimerState.IDLE
        self.elapsed_seconds = 0
        self.total_seconds = 0
        self.start_time = None
        self.timer.stop()
        
        self.stateChanged.emit(self.state)
    
    def get_remaining_seconds(self):
        """获取剩余时间（秒）"""
        if self.mode == TimerMode.POMODORO:
            # 番茄钟模式，返回剩余时间
            return max(0, self.total_seconds - self.elapsed_seconds)
        else:
            # Flowdoro模式，返回已用时间
            return self.elapsed_seconds
    
    def get_progress(self):
        """获取进度（0-1之间的浮点数）"""
        if self.total_seconds <= 0:
            return 0
        
        if self.mode == TimerMode.POMODORO:
            # 番茄钟模式，进度为已用时间比例
            return min(1.0, self.elapsed_seconds / self.total_seconds)
        else:
            # Flowdoro模式，没有明确的进度
            return 0
    
    def get_formatted_time(self):
        """获取格式化的时间字符串（MM:SS）"""
        if self.mode == TimerMode.POMODORO:
            # 番茄钟模式，显示剩余时间
            seconds = max(0, self.total_seconds - self.elapsed_seconds)
        else:
            # Flowdoro模式，显示已用时间
            seconds = self.elapsed_seconds
        
        minutes = seconds // 60
        seconds = seconds % 60
        return f"{minutes:02d}:{seconds:02d}"
    
    def _on_timer_tick(self):
        """计时器滴答事件处理"""
        # 计算已经过的时间
        if self.start_time:
            self.elapsed_seconds = int((datetime.now() - self.start_time).total_seconds())
        
        # 发送计时信号
        self.tick.emit(self.get_remaining_seconds(), self.total_seconds)
        
        # 检查是否完成
        if self.mode == TimerMode.POMODORO and self.elapsed_seconds >= self.total_seconds:
            self.timer.stop()
            
            if self.state == TimerState.WORKING:
                # 工作完成
                if self.current_work_session_id is not None:
                    self.db_manager.end_work_session(self.current_work_session_id)
                    self.current_work_session_id = None
                
                self.workFinished.emit()
            elif self.state == TimerState.BREAKING:
                # 休息完成
                if self.current_break_session_id is not None:
                    self.db_manager.end_break_session(self.current_break_session_id)
                    self.current_break_session_id = None
                
                self.breakFinished.emit()
            
            # 重置状态
            self.state = TimerState.IDLE
            self.elapsed_seconds = 0
            self.start_time = None
            self.stateChanged.emit(self.state) 